<template>
  <n-card title="">
    <template #header>
      <div style="display: flex; align-items: center">
        <span>发布文章（加入了自定义语法，最终效果以预览为准）</span>
        <n-popover placement="bottom" trigger="click">
          <template #trigger>
            <n-icon size="20" style="cursor: help"
              ><HelpCircleOutline
            /></n-icon>
          </template>
          <mySyntaxDialog></mySyntaxDialog>
        </n-popover>
      </div>
    </template>
    <div
      style="
        margin-bottom: 1em;
        text-align: right;
        display: flex;
        gap: 10px;
        justify-content: flex-end;
      "
    >
      <div>
        <n-button type="primary" dashed size="small" @click="btnView">
          <template #icon>
            <n-icon>
              <EyeOutline />
            </n-icon>
          </template>
          预览
        </n-button>
      </div>
      <div>
        <n-button
          type="primary"
          dashed
          size="small"
          @click="handleValidateClick"
        >
          <template #icon>
            <n-icon>
              <PaperPlaneOutline />
            </n-icon>
          </template>
          发送
        </n-button>
      </div>
    </div>
    <div>
      <n-form
        label-placement="left"
        ref="formRef"
        :label-width="80"
        :model="formValue"
        :rules="rules"
        size="medium"
        inline
        style="flex-direction: column"
      >
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="文章标题" path="title">
            <n-input
              v-model:value="formValue.title"
              placeholder="请输入文章标题"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="文章类型" path="articleType">
            <n-select
              v-model:value="formValue.articleType"
              :options="articleTypeList"
              label-field="value"
              value-field="id"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="定时发布">
            <n-date-picker
              style="width: 100%"
              v-model:formatted-value="formValue.publishTime"
              type="datetime"
              clearable
              placeholder="定时发布时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="文章标签" path="articleTag">
            <n-select
              v-model:value="formValue.articleTag"
              :options="articleTagList"
              multiple
              label-field="value"
              value-field="id"
            />
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="是否原创">
            <n-switch v-model:value="formValue.isOriginal" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="原始链接">
            <n-input
              v-model:value="formValue.primitiveLink"
              placeholder="文章的原始链接"
              :disabled="formValue.isOriginal"
            />
          </n-form-item-gi>

          <n-form-item-gi :span="6" label="是否私密">
            <n-switch v-model:value="formValue.isPrivacy" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="访问密码">
            <n-input
              v-model:value="formValue.password"
              placeholder="私密文章访问密码"
              :disabled="!formValue.isPrivacy"
            />
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="是否置顶">
            <n-switch v-model:value="formValue.isTop" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="是否红旗">
            <n-switch v-model:value="formValue.isRedFlag" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="是否评论">
            <n-switch v-model:value="formValue.isComments" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="是否可用">
            <n-switch v-model:value="formValue.enable" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </div>
    <MdEditor
      type="linkAttr"
      target="_blank"
      v-model="formValue.content"
      previewTheme="github"
      codeTheme="gradient"
      style="min-height: 80vh"
      @onUploadImg="onUploadImg"
    />
    <my-dialog
      @closeModal="closeModal"
      :showModal="showModal"
      ref="myDialogRef"
    ></my-dialog>
  </n-card>
</template>

<script setup lang="ts">
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { onMounted, ref } from "vue";
import {
  PaperPlaneOutline,
  EyeOutline,
  HelpCircleOutline,
} from "@vicons/ionicons5";
import {
  createArticle,
  getArticleInfoById,
  updateArticle,
} from "@/api/article.ts";
import { uploadImageFile } from "@/api/file.ts";
import { TAG_DICTIONARY, TagType } from "@/utils/constants";
import { getDictionaryItemByCode } from "@/api/dictionary";
import myDialog from "../../components/contentView.vue";
import mySyntaxDialog from "../../components/syntaxDialog.vue";
import { useRoute } from "vue-router";

const formRef: any = ref(null);
const formValue = ref<any>({
  id: null,
  title: null,
  publishTime: null,
  enable: true,
  articleTag: null,
  isOriginal: true,
  primitiveLink: null,
  isPrivacy: false,
  password: null,
  isTop: false,
  isRedFlag: false,
  isComments: true,
  content: "",
  articleType: null,
});
//表单初始值
const inceptionFormValue = ref({
  id: null,
  title: null,
  publishTime: null,
  enable: true,
  articleTag: null,
  isOriginal: true,
  primitiveLink: null,
  isPrivacy: false,
  password: null,
  isTop: false,
  isRedFlag: false,
  isComments: true,
  content: "",
  articleType: null,
});
const rules = {
  title: {
    required: true,
    trigger: ["blur", "input"],
    message: "请填写文章标题",
  },
  articleTag: {
    type: "array",
    required: true,
    trigger: ["blur", "change"],
    message: "文章还没有标签",
  },
  articleType: {
    required: true,
    trigger: ["blur", "change"],
    message: "文章还没有类型",
  },
};
const articleTypeList = ref();
const articleTagList = ref();
const showModal = ref(false);
const myDialogRef = ref(null);
const route = useRoute();

onMounted(() => {
  if (route.query.id) {
    console.log(route.query.id);
    getArticleInfoById({ id: route.query.id })
      .then((res) => {
        console.log(res);

        formValue.value.id = res.data.id;
        formValue.value.title = res.data.title;
        formValue.value.publishTime = res.data.publishTime;
        formValue.value.enable = res.data.enable;
        formValue.value.articleTag = res.data.articleTag;
        formValue.value.isOriginal = res.data.isOriginal;
        formValue.value.primitiveLink = res.data.primitiveLink;
        formValue.value.isPrivacy = res.data.isPrivacy;
        formValue.value.password = res.data.password;
        formValue.value.isTop = res.data.isTop;
        formValue.value.isRedFlag = res.data.isRedFlag;
        formValue.value.isComments = res.data.isComments;
        formValue.value.content = res.data.content;
        formValue.value.articleType = res.data.articleType;
      })
      .catch((err) => {
        console.log(err);
      });
  } else {
    formValue.value = JSON.parse(JSON.stringify(inceptionFormValue.value));
  }
  articleTypeList.value = [];
  articleTagList.value = [];
  getTagByTypeList(TAG_DICTIONARY.articleTags).then((res) => {
    articleTagList.value = res.data;
  });
  getTagByTypeList(TAG_DICTIONARY.articleType).then((res) => {
    articleTypeList.value = res.data;
  });
});
const getTagByTypeList = (code) => {
  return getDictionaryItemByCode({ code: code })
    .then((res) => {
      return res; // 返回结果
    })
    .catch((error) => {
      console.error("Error:", error); // 捕获错误
      throw error; // 如果发生错误，抛出异常
    });
};
const handleValidateClick = (e) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      if (formValue.value.id == null) {
        createArticle(formValue.value).then((res) => {
          if ((res.code = 200)) {
            window.$message.success(res.message);
            formValue.value = JSON.parse(
              JSON.stringify(inceptionFormValue.value)
            );
            console.log(inceptionFormValue.value);
          } else {
            window.$message.error(res.message);
          }
        });
      } else {
        updateArticle(formValue.value).then((res) => {
          if (res.code == 200) {
            window.$message.success(res.message);
          } else {
            window.$message.error(res.message);
          }
        });
      }
    } else {
      console.log(formValue.value);
      window.$message.error("表单验证错误");
    }
  });
};
const closeModal = () => {
  showModal.value = false;
};
const btnView = () => {
  showModal.value = true;
  myDialogRef.value?.init(formValue.value.content, true);
};
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((rev, rej) => {
        const form = new FormData();
        form.append("file", file);
        console.log(form);
        uploadImageFile(form).then((res) => {
          console.log(res);
          rev(import.meta.env.VITE_APP_FILE_KEY + res.data);
        });
      });
    })
  );

  callback(res.map((item) => item));
};
</script>
